import Card from '@/components/Card';
import Description from '@/components/Description';
import type { ProColumns } from '@/components/Pro/';
import { ProForm, ProFormInstance, ProFormSelect, ProTable } from '@/components/Pro/';

import {
  cabinetComponentControllerGetCabinetUpgradeLogList as tablist,
  cabinetComponentControllerUpgradeIssuance as pushlish,
} from '@/services/ess/cabinetComponent';
import { DescriptionsItemType } from 'antd/es/descriptions';
import React, { useEffect, useRef, useState } from 'react';
import { useIntl, useSearchParams } from 'umi';

import { componentPkgControllerImplListComponentPackages as comList } from '@/services/ess/otaPackVersion';
import { message } from 'antd';
import styles from '../index.less';

const UpdateDetail: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const formRef = useRef<ProFormInstance>();
  const [searchParams] = useSearchParams();
  console.log(searchParams);
  // const stationId = searchParams.get('stationId');
  // const componentId = searchParams.get('componentId');
  // const stationName = searchParams.get('stationsName');
  // const componentName = searchParams.get('componentName');
  // const componentType = searchParams.get('componentType');
  // const updatedTime = searchParams.get('time');
  // const version = searchParams.get('version');

  const {
    stationId,
    componentId,
    stationsName,
    componentName,
    componentType,
    updatedTime,
    version,
    stationComponentId,
  } = JSON.parse(sessionStorage.getItem('LcComponentParams'));
  const reslutObj = {
    componentName: componentName,
    componentType: componentType,
    updatedTime: updatedTime,
    version: version,
  };
  const intl = useIntl();

  const updateStatus = {
    0: intl.formatMessage({ id: 'remoteUpgradeMangment.other.toBeUpgraded' }),
    1: intl.formatMessage({ id: 'remoteUpgradeMangment.other.upgrading' }),
    2: intl.formatMessage({ id: 'remoteUpgradeMangment.other.upgradeSuccessful' }),
    3: intl.formatMessage({ id: 'remoteUpgradeMangment.other.upgradeFailed' }),
    4: intl.formatMessage({ id: 'remoteUpgradeMangment.other.rollbacking' }),
    5: intl.formatMessage({ id: 'remoteUpgradeMangment.other.rollbackSuccessful' }),
    6: intl.formatMessage({ id: 'remoteUpgradeMangment.other.rollbackFailed' }),
  };

  const [baseDes, setBaseDes] = useState<DescriptionsItemType[]>([
    {
      label: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.componentType' }),
      key: 'componentType',
      children: '',
    },
    {
      label: intl.formatMessage({
        id: 'remoteUpgradeMangment.componentManagement.componentNameNotitle',
      }),
      key: 'componentName',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.versionNumber' }),
      key: 'version',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.updateTime' }),
      key: 'updatedTime',
      children: '',
    },
  ]);
  const [ProTableData, setProTableData] = useState<any>([]);
  // const [publistID, setpublistID] = useState<string>('');

  const tableColumns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.SN' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
    },
    {
      dataIndex: 'pkgVersion',
      key: 'pkgVersion',
      hideInSearch: true,
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.versionNumber' }),
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.updateTime' }),
      dataIndex: 'updatedTime',
      key: 'updatedTime',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.other.updateStatus' }),
      dataIndex: 'updateStatus',
      key: 'updateStatus',
      hideInSearch: true,
      render: (text, record) => updateStatus[record.updateStatus], // 这里进行转换
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.componentManagement.upgradePackageStoragePath',
      }),
      dataIndex: 'pkgUrl',
      key: 'pkgUrl',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.remarks' }),
      dataIndex: 'updateDesc',
      key: 'updateDesc',
      hideInSearch: true,
    },
  ];

  const fetchTableData = async () => {
    setLoading(true);
    try {
      const getBaseDes = baseDes.map((item) => ({
        ...item,
        children: reslutObj[item.key] === 'null' ? '--' : reslutObj[item.key],
      }));

      setBaseDes(getBaseDes);
      const params = {
        current: '1',
        pageSize: '20',
        stationComponentId: stationComponentId,
      };
      const reslut = await tablist(params, { stationId: stationId });
      setProTableData(reslut?.data.records || []);
    } catch (error) {
      console.error('Error fetching table data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTableData();
  }, []);
  return (
    <>
      <div className={styles.headerDesc}>
        <div className={styles.headerDesc_title_wrap}>
          <span className={styles.title1}>
            {intl.formatMessage({ id: 'remoteUpgradeMangment.other.Plantcomponentupdate' })}
          </span>
          <span className={styles.title2}>({stationsName})</span>
        </div>
        <Description items={baseDes}></Description>
        <div style={{ marginTop: 20 }}>
          <ProForm
            layout="inline"
            formRef={formRef}
            labelCol={{ style: { width: 160 } }}
            onFinish={async (value) => {
              let param = {
                ...value,
                stationComponentId: stationComponentId,
                pkgId: value.id,
                instructionType: 'UPGRADE',
              };
              let result = await pushlish(param);
              if (result.success) {
                let params = {
                  current: '1',
                  pageSize: '20',
                  stationComponentId: stationComponentId,
                };

                let reslut = await tablist(params, { stationId: stationId });
                setProTableData(reslut?.data.records || []);

                message.success('下发成功');
              }
            }}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({ id: 'remoteUpgradeMangment.other.release' }),
              },
              resetButtonProps: false,
            }}
          >
            <ProFormSelect
              request={async () => {
                let updatamanComparams = {
                  current: '1',
                  pageSize: '20',
                  componentCode: componentId,
                  status: true, //增加的筛选条件只能有可用ota包
                };

                let comreslut = await comList(updatamanComparams);
                console.log(comreslut, 'jsfksdj');
                let comArra = comreslut?.data?.records.map((res) => ({
                  value: res.id,
                  label: res.fileName,
                }));

                return comArra;
              }}
              fieldProps={{
                allowClear: true,
                onChange: async (value) => {
                  if (value !== '') {
                    // let comreslut = await comList(updatamanComparams);
                    // setpublistID(comreslut.filter(res=>res))
                  }
                },
              }}
              width="md"
              name="id"
              label={intl.formatMessage({ id: 'remoteUpgradeMangment.other.selectOtaFile' })}
            />
          </ProForm>
        </div>
      </div>
      <Card
        title={intl.formatMessage({ id: 'remoteUpgradeMangment.other.versionUpdateRecord' })}
        style={{ marginTop: '40px' }}
      >
        <ProTable
          loading={loading}
          columns={tableColumns}
          dataSource={ProTableData}
          search={false}
          rowKey={'pageIndex'}
          toolBarRender={() => []}
        ></ProTable>
      </Card>
    </>
  );
};

export default UpdateDetail;
